using System;
using System.Threading;
using System.Threading.Tasks;

namespace XamlTest
{
   public class MockService : IMockService
   {
      readonly TaskScheduler scheduler;

      public MockService(SynchronizationContext synchronizationContext = null)
      {
         SynchronizationContext.SetSynchronizationContext(synchronizationContext ?? new TestSynchronizationContext());
         scheduler = TaskScheduler.FromCurrentSynchronizationContext();
      }

      public MockServiceMode Mode { get; set; }

      public void Add(int a, int b, Action<int, Exception> completion)
      {
         switch (Mode)
         {
            case MockServiceMode.Immediate:
               completion(a + b, null);
               break;

            case MockServiceMode.Async:
               // This will take a while, better start a task
               Task.Factory
                  .StartNew(() => a + b)
                  .ContinueWith(t => completion(!t.IsFaulted ? t.Result : 0, t.Exception), scheduler);
               break;
   
            default:
               throw new ArgumentOutOfRangeException();
         }
         //else if (a > 20000)
         //{
         //   // This requires the power of the cloud
         //   webService.BeginAdd(a, b, ar =>
         //                             {
         //                                var result = 0;
         //                                Exception error = null;
         //                                try
         //                                {
         //                                   result = webService.EndAdd(ar);
         //                                }
         //                                catch (Exception e)
         //                                {
         //                                   error = e;
         //                                }
         //                                completion(result, error);
         //                             }, null);
         //}
         //else if (b > 20000)
         //{
         //   // A different way to invoke the power of the cloud
         //   if (task != null)
         //      task.Dispose();
         //   task = Task.Factory.FromAsync<int, int, int>(webService.BeginAdd, webService.EndAdd, a, b, null).ContinueWith(t => completion(t.Result, t.Exception), scheduler);
         //}
      }

      public void Multiply(int a, int b, Action<int, Exception> completion)
      {
         throw new NotImplementedException();
      }
   }

   public enum MockServiceMode
   {
      Immediate,
      Async
   }
}